<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="70px">
      <el-form-item label="用户账号" prop="userId" v-has-role="['admin']">
        <el-select v-model="queryParams.userId" placeholder="请选择" @keyup.enter.native="handleQuery">
          <el-option
            v-for="item in userOptions"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="姓名" prop="name">
        <el-input
          style="width: 180px"
          v-model="queryParams.name"
          placeholder="请输入姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="身份证" prop="cardNo">
        <el-input
          style="width: 180px"
          v-model="queryParams.cardNo"
          placeholder="请输入身份证"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="tel">
        <el-input
          style="width: 180px"
          v-model="queryParams.tel"
          placeholder="请输入手机号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" v-hasPermi="['system:query:add']">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd">自主进件
        </el-button>
      </el-col>
      <el-col :span="1.5" v-hasPermi="['system:query:add']">
        <el-button
          type="primary"
          plain
          icon="el-icon-s-custom"
          size="mini"
          @click="addOpen = true">邀请进件
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-search"
          size="mini"
          @click="openQueryBlackList= true">查询行业黑名单
        </el-button>
      </el-col>
      <el-col :span="1.5" v-hasPermi="['system:query:remove']">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete">删除
        </el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"
                     title="展示更多关键字"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="queryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" align="center"/>
      <el-table-column label="进件ID" align="center" prop="queryId" width="60"/>
      <el-table-column label="进件账号" align="center" prop="userName" v-if="$auth.hasRole('admin')"/>
      <el-table-column label="姓名" align="center" prop="name"/>
      <el-table-column label="身份证" align="center" prop="cardNo"/>
      <el-table-column label="手机号" align="center" prop="tel"/>
      <el-table-column label="评分" align="center" prop="score"/>
      <el-table-column label="决策" align="center" prop="decision"/>
      <el-table-column label="三要素认证" align="center" prop="threeElmentAuth"/>
      <el-table-column label="进件时间" align="center" prop="createTime"/>
      <el-table-column label="进件备注" align="center" prop="moreInfo" v-if="columns[0].visible"/>
      <el-table-column label="操作" align="center" width="220">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="openReport(scope.row)">查看风险
          </el-button>
          <el-button
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:query:edit']">修改
          </el-button>
          <el-button
            type="text"
            @click="addBlackList(scope.row)">加入行业黑名单
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"/>

    <!-- 添加或修改进件记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="真实姓名" prop="name">
          <el-input v-model.trim="form.name" :clearable="true" placeholder="请输入姓名"/>
        </el-form-item>
        <el-form-item label="身份证号" prop="cardNo">
          <el-input v-model.trim="form.cardNo" :clearable="true" placeholder="请输入身份证"/>
        </el-form-item>
        <el-form-item label="手机号码" prop="tel">
          <el-input placeholder="请输入或点击生成手机号" v-model.trim="form.tel" :clearable="true">
            <el-button slot="append" @click="makeTel()">生成虚拟手机号</el-button>
          </el-input>
        </el-form-item>
        <!--        <el-form-item label="进件备注" prop="moreInfo" :clearable="true">-->
        <!--          <el-input v-model.trim="form.moreInfo" placeholder="请输入进件备注"/>-->
        <!--        </el-form-item>-->
      </el-form>
      <p class="p">您可点击生成虚拟号码辅助查询避开输入真实号码。但这会降低部分产品查询准确度。</p>
      <p class="p">若您有需求可修改号码提高准确度。平台持续维护数据安全。</p>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="邀请进件" :visible.sync="addOpen">
      <inviteAdd/>
    </el-dialog>

    <el-dialog title="邀请查询" :visible.sync="addReferOpen" :close-on-click-modal="false">
      <inviteQuery v-if="addReferOpen" :item="item"/>
    </el-dialog>

    <el-dialog title="查询行业黑名单" :visible.sync="openQueryBlackList" width="70%"
               :close-on-click-modal="false">
      <el-input :placeholder="`请输入${choice}`" v-model.trim="keyword" :clearable="true">
        <el-select slot="prepend" v-model="choice" placeholder="请选择" style="width: 120px">
          <el-option label="真实姓名" value="真实姓名"></el-option>
          <el-option label="身份证号" value="身份证号"></el-option>
          <el-option label="电话号码" value="电话号码"></el-option>
        </el-select>
        <el-button slot="append" @click="queryBlackList_()" icon="el-icon-search">查询</el-button>
      </el-input>
      <el-table v-loading="queryBlackListLoading" :data="queryBlackList" style="margin-top: 10px">
        <el-table-column label="姓名" align="center" prop="name"/>
        <el-table-column label="身份证" align="center" prop="cardNo"/>
        <el-table-column label="电话" align="center" prop="tel"/>
        <el-table-column label="地址" align="center" prop="location"/>
        <el-table-column label="风险关键字" align="center">
          <template slot-scope="scope">
            <div style="display: flex; justify-content: center; ">
              <div v-for="item in JSON.parse(scope.row.labels)"
                   style="margin: 1px;padding:3px 6px;background-color: red;
               border-radius: 3px;color: #fff;">
                {{ item }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark"/>
      </el-table>
    </el-dialog>

    <el-dialog title="加入行业黑名单" :visible.sync="openAddBlackList" width="500px" :close-on-click-modal="false">
      <el-form ref="blackListForm" :model="blackListForm" :rules="blackListRules" label-width="80px">
        <el-form-item label="真实姓名">
          <el-input v-model="blackListForm.name" placeholder="请输入姓名" :disabled="true"/>
        </el-form-item>
        <el-form-item label="身份证号">
          <el-input v-model="blackListForm.cardNo" placeholder="请输入身份证" :disabled="true"/>
        </el-form-item>
        <el-form-item label="手机号码" prop="tel">
          <el-input v-model="blackListForm.tel" placeholder="请输入手机号" :disabled="true"/>
        </el-form-item>
        <el-form-item label="风险标签" prop="labels">
          <el-select style="width: 100%;" v-model="blackListForm.labels" multiple
                     filterable allow-create placeholder="请选择或输入风险标签">
            <el-option
              v-for="item in labelsOptions"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发生地址">
          <el-input v-model.trim="blackListForm.location" placeholder="请输入地址"/>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model.trim="blackListForm.remark" type="textarea" placeholder="请输入内容。具体行为，过程，金额等"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBlackList">确 定</el-button>
        <el-button @click="openAddBlackList=false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import inviteAdd from "@/views/components/inviteAdd.vue"
  import inviteQuery from "@/views/components/inviteQuery.vue"
  import {quickList, getQuery, delQuery, addQuery, updateQuery} from "@/api/system/query";
  import {validateContacts, validateIdNo, validatePhone} from "@/utils/validate"
  import {addBlacklist, labels, listByElem} from "@/api/system/blacklist";
  import {userName} from "@/api/system/user";

  export default {
    name: "Quick",
    components: {inviteAdd, inviteQuery},
    data() {
      let NCT = (rule, value, callback) => {
        if (!(this.blackListForm.name ||
          this.blackListForm.cardNo ||
          this.blackListForm.tel)) {
          callback(new Error("姓名/身份证号/手机号至少填一项"))
        } else {
          //任意值被填写，清除验证提示
          if (this.blackListForm.name) {
            validateContacts(rule, this.blackListForm.name, callback)
          }
          if (this.blackListForm.cardNo) {
            validateIdNo(rule, this.blackListForm.cardNo, callback)
          }
          if (this.blackListForm.tel) {
            validatePhone(rule, this.blackListForm.tel, callback)
          }
          callback()
        }
      }
      return {
        userOptions: [],
        labelsOptions: [],
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 进件记录表格数据
        queryList: [],
        // 弹出层标题
        title: "",

        // 是否显示弹出层
        open: false,
        openAddBlackList: false,
        openQueryBlackList: false,
        addOpen: false,
        addReferOpen: false,

        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          userId: null,
          name: null,
          cardNo: null,
          tel: null
        },
        columns: [
          {key: 0, label: `进件备注`, visible: false}
        ],
        item: undefined,
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          name: [
            {min: 2, max: 20, message: '姓名长度必须介于 2 和 20 之间', trigger: 'blur'},
          ],
          cardNo: [
            {required: true, validator: validateIdNo, trigger: 'blur'}
          ],
          tel: [
            {required: true, validator: validatePhone, trigger: 'blur'}
          ]
        },
        // 表单参数
        blackListForm: {},
        blackListRules: {
          tel: [
            {required: true, validator: validatePhone, trigger: 'blur'}
          ],
          labels: [
            {required: true, message: '请选择或输入风险标签', trigger: "blur"}
          ]
        },
        keyword: null,
        choice: '真实姓名',
        queryBlackList: [],
        queryBlackListLoading: false
      }
    },
    created() {
      this.getList();
      if (this.$auth.hasRole("admin")) {
        userName().then(response => {
          this.userOptions = response.data;
        });
      }
    },
    methods: {
      makeTel() {
        let phone3 = [
          "130", "131", "132", "133", "134", "135", "136", "137", "138", "139",
          "145", "147", "149", "150", "151", "152", "153", "155", "156", "157", "158", "159",
          "166", "170", "171", "172", "173", "175", "176", "177", "178", "179",
          "180", "181", "182", "183", "184", "185", "186", "187", "188", "189",
          "190", "191", "192", "193", "194", "195", "196", "197", "198", "199",
        ]

        let sj = Math.floor(Math.random() * (phone3.length + 1))

        let phoneNumber = ''; // 手机号第一位为1
        for (let i = 0; i < 8; i++) {
          phoneNumber += Math.floor(Math.random() * 10);  // 其他位为0-9中的任意一个数字
        }
        console.log(phoneNumber)
        this.form.tel = phone3[sj] + phoneNumber
      },


      openQuery(item) {
        updateQuery({
          queryId: item.queryId,
          sourceType: 2
        })
        this.item = item
        this.addReferOpen = true
      },
      openReport(item) {
        this.$router.push({
          path: "/query/report",
          query: {id: item.queryId}
        })
      },
      addBlackList(item) {
        getQuery(item.queryId).then(response => {
          let data = response.data
          this.blackListForm = {
            name: data.name,
            cardNo: data.cardNo,
            tel: data.tel,
            labels: null,
            location: null,
            remark: null
          }
          labels().then(res => {
            this.labelsOptions = res.data
            this.openAddBlackList = true
          })
        });
      },
      submitBlackList() {
        this.$refs.blackListForm.validate(valid => {
          console.log(valid)
          if (valid) {
            addBlacklist({
              ...this.blackListForm,
              labels: JSON.stringify(this.blackListForm.labels)
            }).then(response => {
              this.$modal.msgSuccess("成功");
              this.openAddBlackList = false;
            });
          }
        });
      },
      queryBlackList_() {
        let path
        if (this.choice == '真实姓名') {
          path = 'name=' + this.keyword
        } else if (this.choice == '身份证号') {
          path = 'cardNo=' + this.keyword
        } else if (this.choice == '电话号码') {
          path = 'tel=' + this.keyword
        }
        this.queryBlackListLoading = true
        listByElem(path).then(res => {
          this.queryBlackList = res.data
          this.queryBlackListLoading = false
        })
      },
      /** 查询进件记录列表 */
      getList() {
        this.loading = true;
        quickList(this.queryParams).then(response => {
          this.queryList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false
        this.reset()
      },
      // 表单重置
      reset() {
        this.form = {
          queryId: null,
          userId: null,
          name: null,
          cardNo: null,
          tel: null,
          moreInfo: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.queryId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.title = "自主进件";
        this.open = true;
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const queryId = row.queryId || this.ids
        getQuery(queryId).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改要素信息";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.queryId != null) {
              updateQuery(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addQuery(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const queryIds = row.queryId || this.ids;
        this.$modal.confirm('是否确认删除进件记录编号为"' + queryIds + '"的数据项？').then(function () {
          return delQuery(queryIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('system/query/export', {
          ...this.queryParams
        }, `query_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>
<style scoped>
  .el-select .el-input {
    width: 130px;
  }

  .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }

  .p {
    text-align: center;
  }
</style>
